using System.Collections.Generic;
using UnityEngine;

namespace WorkFlow.Net.Process
{
    public class WebGLLocalStorage : MonoBehaviour
    {
        Dictionary<string,string> _storage = new Dictionary<string, string>();
        private static WebGLLocalStorage _instance;
        public static WebGLLocalStorage Instance {
            get
            {
                if(_instance == null)
                {
                    _instance = new GameObject(nameof(WebGLLocalStorage)).AddComponent<WebGLLocalStorage>();
                    DontDestroyOnLoad(_instance.gameObject);
                }

                return _instance;
            }
        }

        private string _key;
        private string _value;
        private void SetStorageKey(string key)
        {
            _key = key;
        }
        
        private void SetStorageValue(string value)
        {
            _value = value;
            if(_value[0] == '\"')
                _value = _value.Substring(1, _value.Length - 1);
            if(_value[^1] == '\"')
                _value = _value.Substring(0, _value.Length - 1);
        }

        private void SaveStorage()
        {
            if (!string.IsNullOrEmpty(_key))
            {
                _storage[_key] = _value;
                _key = string.Empty;
                _value = string.Empty;
            }
        }
        
        public void ReadStorage(string key)
        {
#if !UNITY_EDITOR && UNITY_WEBGL
            WebGLStorageHelper.readStorage(key);
#endif
        }
        
        public string GetValue(string key)
        {
            return _storage.TryGetValue(key, out var value) ? value : string.Empty;
        }
    }
    
#if !UNITY_EDITOR && UNITY_WEBGL
    public static class WebGLStorageHelper
    {
        [System.Runtime.InteropServices.DllImport("__Internal")]
        public static extern string readStorage(string key);
    }
#endif
}

